package com.star.bookkeeping.controller;


import android.content.Context;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.star.bookkeeping.database.BillDBHelper;
import com.star.bookkeeping.entity.AjaxResult;
import com.star.bookkeeping.entity.BillInfo;

import java.util.List;

public class JavaScriptInterface {
    BillDBHelper billDBHelper = null;

    public JavaScriptInterface(Context context) {
        billDBHelper = BillDBHelper.getInstance(context);
    }

    @JavascriptInterface
    public String saveBillInfo(String billInfoJson) {
        // 处理保存账单信息的逻辑
        JSONObject jsonObject = JSON.parseObject(billInfoJson);
        BillInfo billInfo = new BillInfo();
        billInfo.date = jsonObject.getString("date");
        billInfo.type = jsonObject.getIntValue("type");
        billInfo.amount = jsonObject.getDouble("amount");
        billInfo.remark = jsonObject.getString("remark");
        long code = billDBHelper.save(billInfo);
        // 假设返回一个字符串结果
        Log.d("saveBillInfo", billInfoJson);
        if (code > -1) {
            return JSON.toJSONString(AjaxResult.success(code));
        } else {
            return JSON.toJSONString(AjaxResult.error("存储失败", code));
        }

//        return "Bill info saved successfully";
    }

    /**
     * @param yearMonth 2035-09
     * @return
     */
    @JavascriptInterface
    public String queryByMonth(String yearMonth) {
        try {
            // 处理保存账单信息的逻辑
            List<BillInfo> billInfos = billDBHelper.queryByMonth(yearMonth);
            // 假设返回一个字符串结果
            String json = JSON.toJSONString(AjaxResult.success("", billInfos));
//            Log.d("queryByMonth", json);

            return json;
        } catch (Exception e) {
            return JSON.toJSONString(AjaxResult.error("查询异常", e.getMessage()));
        }
    }

    @JavascriptInterface
    public void initWebView(WebView webView) {
        webView.addJavascriptInterface(this, "android");
    }
}
